package cn.gz.demo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Liuyz on 2019/12/27.
 */

public class StringUtils {

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.NO_CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    /**
     * 将Base64编码转换为图片
     *
     * @param base64Str
     * @param path
     * @return true
     */
    public static boolean base64ToFile(String base64Str, String path) {
        byte[] data = Base64.decode(base64Str, Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 传入url 先压缩 后转为base64
     *
     * @param srcPath
     * @return
     */
    public static String bitmapToString(String srcPath, int picSize, int reWidth, int reHeigth) {
        try {
            // 设置参数
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
            BitmapFactory.decodeFile(srcPath, options);
            int height = options.outHeight;
            int width = options.outWidth;
            if (reHeigth <= 0 || reWidth <= 0) {
                reHeigth = height;
                reWidth = width;
            }
            options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
//            inSampleSize的作用就是可以把图片的长短缩小inSampleSize倍，所占内存缩小inSampleSize的平方
            options.inSampleSize = caculateSampleSize(options, reWidth, reHeigth);

            Bitmap bm = BitmapFactory.decodeFile(srcPath, options); // 解码文件
            if (bm == null)
                return "";
            return compressImageToBase64(bm, picSize);//压缩好比例大小后再进行质量压缩
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 计算出所需要压缩的大小
     *
     * @param options
     * @param reqWidth  我们期望的图片的宽，单位px
     * @param reqHeight 我们期望的图片的高，单位px
     * @return
     */
    public static int caculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int sampleSize = 1;
        int picWidth = options.outWidth;
        int picHeight = options.outHeight;
        if (picWidth > reqWidth || picHeight > reqHeight) {
            int halfPicWidth = picWidth / 2;
            int halfPicHeight = picHeight / 2;
            while (halfPicWidth / sampleSize > reqWidth || halfPicHeight / sampleSize > reqHeight) {
                sampleSize *= 2;
            }
        }
        return sampleSize;
    }

    public static String compressImageToBase64(Bitmap image, int picSize) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
//        int options = 100;
//        while (options > 0 && baos.toByteArray().length / 1024 >= picSize) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
//            baos.reset();//重置baos即清空baos
//            image.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
//            options -= 5;//每次都减少10
//        }
        if (picSize > 0) {
            long picL = baos.toByteArray().length;
            int picS = (int) (picL / 1024);
            if (picS > picSize) {
                int options = (int) (picSize * 1.0 / picS * 100);
                LogUtil.showLog("......picL......" + picL);
                LogUtil.showLog("......picS......" + picS);
                LogUtil.showLog("......options......" + options);

                baos.reset();//重置baos即清空baos
                image.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
        }
        byte[] bytes = baos.toByteArray();
        LogUtil.showLog("......bytes......" + bytes.length);
        return Base64.encodeToString(bytes, Base64.NO_CLOSE);
    }


    /**
     * base64 保存图片到本地
     *
     * @param base64Str
     * @param path
     * @return
     */
    public static boolean base64ToFile(Context context, String base64Str, String path) {
        byte[] bytes = null;
        boolean isOk = false;
        String endMsg = base64Str;
        File pFile = null;
        try {
            if (base64Str.contains(";base64,"))
                endMsg = base64Str.substring(base64Str.indexOf(";base64,") + 8, base64Str.length());
            bytes = Base64.decode(endMsg, Base64.DEFAULT);
            if (bytes != null) {
                Bitmap mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                if (!TextUtils.isEmpty(path)) {
                    pFile = new File(path);
                } else {
                    String pPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "良策金服" + File.separator; // 文件地址
                    File file = new File(pPath);
                    // 如果sd卡没有文件夹就创建一个文件夹
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    pFile = new File(file, System.currentTimeMillis() + ".png");
                }
                FileOutputStream fos = new FileOutputStream(pFile);
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
                isOk = true;
            } else {
                isOk = false;
            }
        } catch (Exception e) {
            isOk = false;
            e.printStackTrace();
        }
        return isOk;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
}
